<template>
  <div class="approval-container">
    <!-- 搜索条件区域 -->
    <div class="search-wrapper">
      <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form" label-width="85px" style="text-align: left">
        <div>
          <el-row>
            <el-col :span="6">
              <el-form-item label="套餐编号" prop="comboCode">
                <el-input v-model="searchForm.comboCode" placeholder="套餐编号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: center;">
              <el-form-item label="套餐名称" prop="comboName">
                <el-input v-model="searchForm.comboName" placeholder="套餐名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: center;">
              <el-form-item label="类型" prop="type">
                <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
                  <el-option label="早餐" value="1"></el-option>
                  <el-option label="午餐" value="2"></el-option>
                  <el-option label="晚餐" value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: right;">
              <el-form-item label="状态" prop="status">
                <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                  <el-option label="正常" value="0"></el-option>
                  <el-option label="停用" value="1"></el-option>
                  <el-option label="审核中" value="2"></el-option>
                  <el-option label="不同意" value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div style="margin-top: 10px;">
          <el-row>
            <el-col :span="6" >
              <el-form-item label="创建人" prop="createBy">
                <el-input v-model="searchForm.createBy" placeholder="创建人" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: center;">
              <el-form-item label="创建日期" prop="createTime">
                <el-date-picker v-model="searchForm.createTime" type="date" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: center;">
              <el-form-item label="生效日期" prop="startDate">
                <el-date-picker v-model="searchForm.startDate" type="date" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: right;">
              <div class="search-actions">
                <el-button style="background-color: #4C6EE2;color: white;" size="small" @click="handleSearch">搜索</el-button>
                <el-button size="small" @click="resetSearch">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="status-filter" style="display: flex;justify-content: space-between;">
      <div>
        <el-radio-group v-model="radio" style="margin-top: 9px;margin-left: 17px;" @input="inputGroup">
          <el-radio :label="1">全部</el-radio>
          <el-radio :label="2">正常</el-radio>
          <el-radio :label="3">停用</el-radio>
          <el-radio :label="4">审核</el-radio>
          <el-radio :label="5">不同意</el-radio>
          <el-radio :label="6">早餐</el-radio>
          <el-radio :label="7">午餐</el-radio>
          <el-radio :label="8">晚餐</el-radio>
        </el-radio-group>
      </div>
      <div style="position: relative;">
        <div style="position: absolute;top: 40px;width: 170px;height: 330px;left: 0; background-color: white; border-radius: 10px;z-index: 9999;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);padding: 10px;overflow: auto;padding-top: 20px;" v-if="columnShow">
            <!-- <div style="text-align: right;margin-bottom: 10px;">
              <i class="el-icon-close" @click="columnShow = false"></i>
            </div> -->
            <div v-for="(item,index) in dictData" :key="index" style="display: flex;justify-content: space-between;padding-bottom: 15px;">
                <div style="font-size: 15px;">
                   {{ item.dictLabel }}
                </div>

                <div>
                  <el-switch
                  @change="(e)=>onchangeSwitch(e,item)"
                    v-model="item.dictValue"
                    active-value="1"
                    inactive-value="0">
                  </el-switch>
                </div>
            </div>
          </div>
          <el-button type="primary" size="small" plain @click="columnShow = !columnShow" >显示列</el-button>
          <el-button
            class="my-recipe-btn"
            size="small"
            @click="previewShow = true">
            菜谱预览
          </el-button>
        <el-button type="primary" size="small" plain icon="el-icon-plus" @click="handleAdd" v-hasPermi="['food:combo:add']">新增</el-button>
        <el-button type="success" size="small" plain icon="el-icon-edit" @click="handleBatchEdit" v-hasPermi="['food:combo:edit']">修改</el-button>
        <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出</el-button>
        <el-button type="danger" size="small" plain icon="el-icon-delete-solid" @click="handleBatchDelete" v-hasPermi="['food:combo:remove']">删除</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper">
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="loading"
        :header-cell-style="{ background: '#f8f8f9' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column prop="comboCode" label="套餐编号" width="150"></el-table-column>
        <el-table-column prop="comboName" label="套餐名称" width="120" align="left"></el-table-column>
        <el-table-column prop="type" label="类型" width="100" align="left">
          <template slot-scope="scope">
            {{ getTypeText(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="coverImage" label="套餐图片" width="150" align="left">
          <template slot-scope="scope">
            <div v-if="scope.row.coverImage" style="display: flex; flex-wrap: wrap;">
              <el-image 
                v-for="(img, index) in parseImageUrls(scope.row.coverImage)" 
                :key="index"
                style="width: 30px; height: 30px; border-radius: 50%; margin-right: 5px;"
                :src="img"
                :preview-src-list="parseImageUrls(scope.row.coverImage)"
                fit="cover"
              ></el-image>
            </div>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="listItem" label="菜品" width="200" align="left" show-overflow-tooltip v-if="tableColumn.菜品 == 1">
          <template slot-scope="scope">
            <div v-if="scope.row.listItem" style="display: flex;">
              <div v-for="(item,index) in scope.row.listItem" :key="index">
                <!-- {{ item.type }} -->
                <div v-if="item.type">
                    {{ dict.type.foot_cuisine_type.filter(el=>el.value == item.type)[0].label + ":" + item.foodDish.foodName + ","}}
                </div>
              </div>
            </div>
            <span v-else>无菜品</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="现售价" width="100" align="right" v-if="tableColumn.现售价 == 1">
          <template slot-scope="scope" v-if="scope.row.price">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="originalPrice" label="原价" width="100" align="right" v-if="tableColumn.原价 == 1">
          <template slot-scope="scope" v-if="scope.row.originalPrice">
            ¥{{ scope.row.originalPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="num" label="最大供应量" width="120" align="left"></el-table-column>
        <!-- <el-table-column prop="saleAllNum" label="积累销量" width="120" align="left"></el-table-column> -->
        <el-table-column prop="saleAllNum" label="积累销量" align="left" width="120" v-if="tableColumn.积累销量 == 1">
              <template slot-scope="scope">
                {{ scope.row.saleAllNum < 0 ? 0 : scope.row.saleAllNum }}
              </template>
            </el-table-column>
        <el-table-column prop="limitPerUser" label="限购数量（-1不限）" width="150" align="left">
          <template slot-scope="scope">
           {{ scope.row.limitPerUser == -1 ? "不限" : scope.row.limitPerUser }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="'success'" v-if="scope.row.status === '0'">
              正常
            </el-tag>
            <el-tag style="background-color: rgb(254, 238, 238);color: red;border: none;" v-if="scope.row.status === '1'">
              停用
            </el-tag>
            <el-tag style="background-color: rgb(237, 240, 252);color: #4C6EE2;" v-if="scope.row.status === '2'">
              审核中
            </el-tag>
            <el-tag style="background-color: rgb(254, 238, 238);color: red;border: none;" v-if="scope.row.status === '3'">
              不同意
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="生效时间" width="120" align="left" show-overflow-tooltip></el-table-column>
        <el-table-column prop="validDays" label="开放时间" width="190" align="left" show-overflow-tooltip>
          <template slot-scope="scope">
            <div style="" v-if="scope.row.day1 != null && scope.row.day1 != undefined">
              <span v-for="(item,index) in 7" :key="index">
                {{ scope.row["day" + (index + 1)] == 1 ? (openingHoursList[index].label + "、") : "" }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序"></el-table-column>

        <el-table-column prop="createBy" label="创建人" width="100" align="left"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" align="left"></el-table-column>
        <el-table-column prop="remark" label="备注" width="160" align="left" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)" style="color: #4C6EE2;" v-hasPermi="['food:combo:edit']">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" style="color: #4C6EE2;" v-hasPermi="['food:combo:remove']">删除</el-button>
            <el-button type="text" size="small" @click="particulars(scope.row)" style="color: #4C6EE2;">详情</el-button>
            <el-button type="text" size="small" v-hasPermi="['food:combo:approval']" v-if="scope.row.status == 2" @click="particulars(scope.row)" style="color: #4C6EE2;">待审核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <pagination v-show="pagination.total > 0" :total="pagination.total" :page.sync="pagination.pageNum" :limit.sync="pagination.pageSize" @pagination="fetchData" />
      </div>
    </div>

    <!-- 新增/编辑弹框 -->
    <el-dialog
      :title="dialogTitle"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="50%"
      style="border-radius: 10px;"
      @close="resetForm"
    >
      <template #title>
        <div class="custom-dialog-title">
          <div style="display: flex;border-bottom: 1px solid rgba(0, 0, 0, 0.05);padding-bottom: 20px;padding-left: 30px;">
            <div style="background-color: #4C6EE2;border-radius: 20px;width: 4px;margin-right: 8px;height: 20px;margin-top: 6.5px;"></div>
            <span class="title-text" style="font-family: Source Han Sans;font-size: 20px;font-weight: 500;line-height: 31px;text-align: center;letter-spacing: normal;color: #3D3D3D;">{{ dialogTitle }}</span>
          </div>
        </div>
      </template>
      <div style="font-family: Source Han Sans;font-size: 20px;font-weight: 500;line-height: 31px;margin-left: 30px;display: flex;letter-spacing: normal;color: #3D3D3D;">
        <img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 5px;">
        基本信息
      </div>
      <el-form
        ref="foodForm"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="dialogN"
        style="padding: 30px;padding-top: 10px;"
        label-position="top"
        size="medium"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="套餐名称" prop="comboName">
              <el-input v-model="form.comboName" placeholder="请输入套餐名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="热量" prop="heat">
              <el-input v-model="form.heat" placeholder="请输入热量" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="现售价" prop="price">
              <el-input v-model="form.price" type="number" :min="0" placeholder="请输入现售价" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="原价" prop="originalPrice">
              <el-input v-model="form.originalPrice" type="number" :min="0" placeholder="请输入原价" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大供应量" prop="num">
              <el-input v-model="form.num" type="number" @input="OnchangeInput" :min="0" placeholder="请输入最大供应量" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生效时间" prop="startDate">
              <el-date-picker
                style="width: 100%;"
                v-model="form.startDate"
                type="date"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="类型" prop="type" >
              <!-- {{ dict.type.food_eat_type.filter(el=>el.value == form.type) }} -->

              <el-select v-model="form.type" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="(item,index) in moldList"
                  :key="index"
                  :label="item.label"
                  :value="Number(item.value)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开放时间" prop="openingHours">
              <el-select v-model="form.openingHours" multiple placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="(item,index) in openingHoursList"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        
          <el-col :span="4">
        <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
        <el-form-item label="最大限购(-1不限)" prop="limitPerUser">
              <el-input-number v-model="form.limitPerUser" controls-position="right" :min="-1" />
            </el-form-item>
          </el-col>
        </el-row>
      <el-row>
        <el-col :span="8" v-hasPermi="['food:combo:approval']">
            <el-form-item label="状态" prop="status" v-if="form.status !=2 && form.status!=3">
              <el-select v-model="form.status" placeholder="请选择" style="width: 95%;">
                <el-option
                  v-for="(item,index) in statusList"
                  :key="index"
                  :label="item.label"
                  :value="String(item.value)"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;">
          <img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;margin-top: -5px;">
          套餐信息
          <el-button plain style="background-color: rgb(237, 240, 252);color: #4C6EE2;border: 1px solid #4C6EE2;" @click="addIngredients">添加菜品</el-button>
          （总价格：{{totalPrice}}）
        </div>

        <el-row :gutter="20" v-for="(item,index) in form.listItem" :key="index">
          <el-col :span="8">
            <el-form-item 
              label="菜品类型" 
              :prop="`listItem.${index}.type`" 
              :rules="{
                required: true,
                message: '请选择菜品类型',
                trigger: 'change'}" 
            >
              <el-select 
                v-model="item.type" 
                placeholder="请选择" 
                style="width: 100%;"
                clearable 
              >
                <el-option
                  v-for="(items,index) in dict.type.foot_cuisine_type"
                  :key="index"
                  :label="items.label"
                  :value="items.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item 
              label="菜品"
              :prop="`listItem.${index}.foodDish.foodId`" 
              :rules="{
                required: true,
                message: '请选择菜品',
                trigger: 'change'}"  
            >
            <el-select 
              v-model="item.foodDish.foodId" 
              placeholder="请选择" 
              style="width: 80%;"
              filterable
              clearable 
              @change="handleFoodChange(item.foodDish.foodId, item)"  
            >
              <el-option
                v-for="(items, index) in ingredientList.filter(el => el.status != 1)"
                :key="index"
                :label="items.foodName"
                :value="items.foodId"
              >
                <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                  <span>{{ items.foodName }}</span>
                  <span style="color: #67C23A; font-weight: 500;">￥{{ items.price }}</span>
                </div>
              </el-option>
            </el-select>
            <!-- {{ form.listItem.length > 1 }} -->
              <i 
                class="el-icon-delete" 
                v-if="form.listItem.length > 1" 
                @click="deleteFoodItems(index)"
                style="margin-left: 5px; cursor: pointer;"
              ></i>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="套餐描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入套餐描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="过敏源" prop="allergy">
          <el-input 
            v-model="form.allergy"
            type="textarea"
            :rows="3"
            placeholder="请输入过敏源"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="套餐图片" prop="coverImage">
              <el-upload
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="handleImageChange"
                :file-list="fileList"
                :before-upload="beforeUpload"
                :on-remove="handleRemove"
                multiple
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="dialogVisible = false" style="background-color: white;color: #4C6EE2;border: 1px solid #4C6EE2;">取 消</el-button>
                <el-button @click="fanhui" style="background-color: white;color: #4C6EE2;border: 1px solid #4C6EE2;" v-if="searchForm.comboCode && searchForm.comboCode == comboCode">取消并返回</el-button>
        <el-button type="primary" @click="handleSubmit" style="background-color: #4C6EE2;color: white;" :loading="submitting">确 定</el-button>
        <el-button type="primary" @click="handleSubmit(1)" style="background-color: #4C6EE2;color: white;" :loading="submitting" v-if="searchForm.comboCode && searchForm.comboCode == comboCode">确定并返回</el-button>
      </div>
    </el-dialog>
    
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="previewShow"
      width="450px"
      class="pervoewClass"
      :show-close="false"
      style="background-color: none;"
      >
      <div>
         <preview></preview>
      </div>
    </el-dialog>
    <package-details-dialog ref="packageDialog" @oneditEmit="propNneditEmit" @getlist="onGetListEmit" :packdetaId="packdetaId" v-if="isTrueShow"></package-details-dialog>
  </div>
</template>

<script>
import { getList, ComboAdd, ComboUpdate, deleteCombo, ComboParticulars,ComboDelPron } from '@/api/combo'
import { getToken } from "@/utils/auth"
import { uploading, getList as getlists } from '@/api/cuisine'
import PackageDetailsDialog from './PackageDetailsDialog.vue'
import { listData, getData, delData, addData, updateData } from "@/api/system/dict/data"
import preview from './preview.vue'

export default {
  name: "ComboManagement",
  dicts: ['foot_cuisine_type',"food_eat_type"],
  components: {
    PackageDetailsDialog,
    preview
  },
  data() {
    return {
      previewShow:false,
      tableColumn:{},
      columnShow: false,
      dictData:[],
      ingredientList: [],
      isTrueShow: false,
      radio: 1,
      statusList: [
        { value: 0, label: "正常" },
        { value: 1, label: "停用" }
      ],
      searchForm: {
        comboCode: '',
        comboName: '',
        type: null,
        status: '',
        createBy: '',
        createTime: '',
        startDate: ''
      },
      packdetaId: "",
      openingHoursList: [
        { value: 1, label: "周一" },
        { value: 2, label: "周二" },
        { value: 3, label: "周三" },
        { value: 4, label: "周四" },
        { value: 5, label: "周五" },
        { value: 6, label: "周六" },
        { value: 7, label: "周日" }
      ],
      upload: {
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      loading: false,
      tableData: [],
      multipleSelection: [],
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增套餐',
      submitting: false,
      fileList: [], // 上传文件列表
      objlist: {},
      comboCode:"",
      form: {
        comboName: '',
        coverImage: '', // 存储多个图片URL的JSON字符串
        price: null,
        originalPrice: null,
        num: null,
        sales: '',
        delFlag: '',
        startDate: "",
        createBy: '',
        createTime: '',
        updateBy: '',
        openingHours: [],
        updateTime: '',
        type: "",
        limitPerUser:-1,
        remark: '',
        status: 0,
        sort:0,
        listItem: [
          {
            comboCode: "",
            foodCode: "",
            foodDish: {
              foodName: "",
              foodId: "",
              type: "",
              foodCode: ""
            }
          }
        ],
        description: ''
      },
      moldList: [
        { value: 1, label: "早餐" },
        { value: 2, label: "午餐" },
        { value: 3, label: "晚餐" }
      ],
      rules: {
        comboName: [
          { required: true, message: '请输入套餐名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入最大供应量', trigger: 'blur' }
        ],
        // openingHours: [
        //   { required: true, message: '请选择开放时间', trigger: 'blur' }
        // ],
        sort: [
          { required: true, message: '请填写排序', trigger: 'blur' }
        ],
        // sort
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ],
        // coverImage: [
        //   { required: true, message: '请上传至少一张图片', trigger: 'change' }
        // ],
        'listItem': [
          { 
            validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error('至少需要添加一个食材'));
              } else {
                const isValid = value.every(item => {
                    return item.foodDish?.type && item.foodDish?.foodId;
                });
                if (!isValid) {
                  callback(new Error('请填写完整的食材和用量'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  
  computed: {
    totalPrice() {
      return this.form.listItem.reduce((sum, item) => {
        const matchedIngredient = this.ingredientList.find(
          ing => ing.foodId === item.foodDish.foodId
        );
        return sum + (matchedIngredient?.price || 0);
      }, 0);
    }
  },

  created() {
    if (this.$route.query.comboCode) {
      this.searchForm.comboCode = this.$route.query.comboCode;
      this.comboCode = this.$route.query.comboCode
    }
    this.fetchData()
    this.dictdata()

    this.infredient()
    console.log(this.$store.state.user.roles.filter(el => el == "canteen_admin"))
    console.log(this.$route.query.comboCode)
    
  },


  methods: {
    fanhui() {
      this.$router.go(-1);
    },
    async dictdata() {
        const res = await listData({
            dictType: "combo_column",
            pageSize: 99,
            pageNum:1
           })
           console.log(res)
        this.dictData = res.rows

        const T = JSON.parse(JSON.stringify(res.rows));
        const U = {}
        T.forEach(el => {
          U[el.dictLabel] = el.dictValue
        })

        this.tableColumn = U;
        console.log(this.tableColumn)
      },
      async onchangeSwitch(e,item) {
        console.log(e, item)
        const res = await updateData(item);
        if (res.code == 200) {
          this.dictdata()
          this.$message.success('操作成功');
        }
      },
    // 解析图片URL数组
    parseImageUrls(coverImage) {
      try {
        return JSON.parse(coverImage || '[]').map(el=>el.url)
      } catch (e) {
        return []
      }
    },

    onGetListEmit() {
      this.isTrueShow = false;
      setTimeout(() => {
        this.fetchData()
      },500)
    },

    handleExport() {
      this.download('food/combo/export', {
        ...this.searchForm
      }, `套餐导出${new Date().toISOString().slice(0, 10)}.xlsx`)
    },

    onChangePre() {
      this.form.originalPrice = this.totalPrice;
    },

    OnchangeInput(val) {
      if (this.from.limitPerUser == null || this.from.limitPerUser == undefined || this.from.limitPerUser == "") {
        return true
      }
      if (this.from.limitPerUser == -1) {
        return true
      }
      if (val > this.from.limitPerUser) {
        this.form.num = this.from.limitPerUser;
        this.$message({
          message: '超过最大限制',
          type: 'warning'
        });
      }
    },

    async particulars(val) {
      // this.isTrueShow = false
      this.isTrueShow = true
      this.$nextTick(() => {
        this.packdetaId = val.comboId
        this.$refs.packageDialog.openDialog()
      })
    },

    handleFoodChange(selectedFoodId, item) {
    // 检查选中的 foodId 是否在 ingredientList 中存在
    const isValid = this.ingredientList.some(
      food => food.foodId === selectedFoodId && food.status != 1
    );
    
      // 如果无效，清空选择
    console.log(isValid)
    if (!isValid) {
      item.foodDish.foodId = ''; // 或者设为 null/undefined
    }
  },

    inputGroup() {
      if (this.radio == 2) {
        this.searchForm.status = '0'
        this.searchForm.type = ''
      } else if (this.radio == 3) {
        this.searchForm.status = '1'
        this.searchForm.type = ''
      } else if (this.radio == 4) {
        this.searchForm.status = '2'
        this.searchForm.type = ''
      } else if (this.radio == 5) {
        this.searchForm.status = '3'
        this.searchForm.type = ''
      } else if (this.radio == 6) {
        this.searchForm.status = ''
          this.searchForm.type = '1'
      } else if (this.radio == 7) {
        this.searchForm.status = ''
          this.searchForm.type = '2'
      } else if (this.radio == 8) {
        this.searchForm.status = ''
          this.searchForm.type = '3'
      } else {
        this.searchForm.type = ''
        this.searchForm.status = ''
      }
      this.fetchData()
    },

    propNneditEmit(val) {
      this.handleEdit(val)
    },

    getTypeText(type) {
      const typeMap = {
        1: '早餐',
        2: '午餐',
        3: '晚餐'
      }
      return typeMap[type] || '未知'
    },

    handleImport() {
      this.upload.title = "套餐导入"
      this.upload.open = true
    },

    importTemplate() {
      const link = document.createElement('a')
      link.href = './套餐导入模板.xlsx'
      link.download = '套餐导入模板.xlsx'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },

    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.fetchData()
    },

    deleteFoodItems(index) {
      this.form.listItem.splice(index, 1)
    },

    async infredient() {
      const data = await getlists({ pageNum: 1, pageSize: 99999999 })
      this.ingredientList = data.rows
    },
  
    // 获取套餐列表
    async fetchData() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
        const data = await getList(params)
        this.tableData = data.rows
        this.pagination.total = data.total
        if (this.$route.query.comboCode && this.$route.query.comboCode == this.searchForm.comboCode) {
             const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
          setTimeout(() => {
            this.handleEdit(this.tableData[0])
                      loading.close();
          },1500)
        }
      } catch (error) {
        console.error(error)
        this.$message.error('获取套餐列表失败')
      } finally {
        this.loading = false
      }
    },
  
    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1
      this.fetchData()
    },
  
    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.handleSearch()
    },
  
    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
  
    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.fetchData()
    },
  
    // 表格选择变化
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
  
    // 新增套餐
    handleAdd() {
      this.dialogTitle = '新增套餐'
      this.resetForm()
      // this.form.sort = Number(this.tableData.length + 1)
      // this.form.limitPerUser = -1
      this.form.status = "0"
      this.dialogVisible = true
    },

    // 图片上传前的校验
    beforeUpload(file) {
      const isImage = file.type.includes('image/')
      const isLt5M = file.size / 1024 / 1024 < 5
      
      if (!isImage) {
        this.$message.error('只能上传图片文件！')
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB！')
      }
      
      return isImage && isLt5M
    },

    // 处理图片变化
    async handleImageChange(file, fileList) {
      this.fileList = fileList
      if (file.status === 'ready') {
        try {
          const formData = new FormData()
          formData.append('file', file.raw)
          
          const response = await uploading(formData)

          if (response.code === 200) {
            // // 获取当前已有的图片URL数组
            // let currentImages = []
            // try {
            //   currentImages = JSON.parse(this.form.coverImage || '[]')
            // } catch (e) {
            //   currentImages = []
            // }

            // // 添加新图片URL
            // currentImages.push(response.data)
            // this.form.coverImage = JSON.stringify(currentImages)

            // this.$message.success('图片上传成功')

                     // 更新当前文件的上传状态和URL
                     const index = this.fileList.findIndex(item => item.uid === file.uid);
            if (index !== -1) {
              this.$set(this.fileList[index], 'url', response.data);
              this.$set(this.fileList[index], 'name', file.name);
              this.$set(this.fileList[index], 'status', 'success');
            }
            
            // 更新form.aptUrl，包含所有图片URL
            const urls = this.fileList.map(item => item.url || item.response?.data).filter(url => url);
            console.log(this.fileList)
            console.log(urls)
            // this.form.aptUrl = urls.join(',');
            this.form.coverImage = JSON.stringify(this.fileList)
            
            this.$message.success('图片上传成功');
          } else {
            throw new Error(response.data || '上传失败')
          }
        } catch (error) {
          console.error('上传失败:', error)
          this.$message.error(error.message)
          // 移除上传失败的文件
          this.fileList = this.fileList.filter(f => f.uid !== file.uid)
        }
      }
    },

    // 移除图片
    handleRemove(file, fileList) {
      this.fileList = fileList
      
      // 从coverImage中移除对应的图片
      const url = file.url || file.response?.data
      console.log(url)
      if (url) {
        try {
          let currentImages = JSON.parse(this.form.coverImage || '[]')
          currentImages = currentImages.filter(img => img.url !== url)
          this.form.coverImage = JSON.stringify(currentImages)
        } catch (e) {
          console.error('解析图片失败:', e)
          this.form.coverImage = '[]'
        }
      }

      console.log(this.fileList)
    },
  
    // 编辑套餐
    handleEdit(row) {
      this.dialogTitle = '编辑套餐'
      
      // 处理开放时间
      row.openingHours = []
      for (let index = 1; index <= 7; index++) {
        if (row["day" + index] == 1) {
          row.openingHours.push(index)
        }
      }

      // 复制表单数据
      this.form = JSON.parse(JSON.stringify(row))

      this.form.listItem.forEach(el => {
         const isValid = this.ingredientList.some(
           food => food.foodId == el.foodDish.foodId && food.status != 1
        );

        if (!isValid) {
          el.foodDish.foodId = ""
        }
      })

    //   const isValid = this.ingredientList.some(
    //   food => food.foodId === selectedFoodId && food.status != 1
    // );
    
    //   // 如果无效，清空选择
    // console.log(isValid)
    // if (!isValid) {
    //   item.foodDish.foodId = ''; // 或者设为 null/undefined
    // }
      const T = this.moldList
      console.log(T)
      if (T.length < 1) {
         if (this.form.type == 1) {
           this.form.type = "早餐"
        }

        if (this.form.type == 2) {
           this.form.type = "午餐"
        }

        if (this.form.type == 3) {
           this.form.type = "晚餐"
         }
      }
      // 初始化图片列表
      this.fileList = []
      try {
        const images = JSON.parse(this.form.coverImage || '[]')
        images.forEach(url => {
          this.fileList.push({
            name: url.name,
            url: url.url
          })
        })
      } catch (e) {
        console.error('解析图片失败:', e)
      }
      
      this.dialogVisible = true
    },
  
    // 批量编辑
    handleBatchEdit() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条记录')
        return
      }
      if (this.multipleSelection.length > 1) {
        this.$message.warning('暂不支持批量编辑')
        return
      }
      this.handleEdit(this.multipleSelection[0])
    },
  
    // 删除套餐
    handleDelete(row) {
      this.$confirm(`确定删除套餐【${row.comboName}】吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {

          if (this.$store.state.user.roles.filter(el => el == "canteen_admin").length > 0) {
              await ComboDelPron(row.comboId)
          } else {
            await deleteCombo(row.comboId)
          }
          this.$message.success('删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
  
    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条记录')
        return
      }
      const names = this.multipleSelection.map(item => item.comboName).join('、')
      this.$confirm(`确定删除选中的${this.multipleSelection.length}条记录吗?【${names}】`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.multipleSelection.map(item => item.comboId).join(',')
          if (this.$store.state.user.roles.filter(el => el == "canteen_admin").length > 0) {
              await ComboDelPron(ids)
          } else {
            await deleteCombo(ids)
          }
          
          this.$message.success('批量删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
  
    addIngredients() {
      this.form.listItem.push({
        comboCode: "",
        foodCode: "",
        foodDish: {
          foodName: "",
          foodId: "",
          type: "",
          foodCode: "", 
        }
      })
    },
  
    // 重置表单
    resetForm() {
      this.form = {
        comboCode: '',
        comboName: '',
        coverImage: '', // 重置为空的JSON字符串
        price: null,
        originalPrice: null,
        num: null,
        sales: '',
        type: null,
        startDate: '',
        endDate: '',
        delFlag: '',
        openingHours: [],
        status: '0',
        createBy: this.$store.state.user.name,
        createTime: '',
        updateBy: '',
        updateTime: '',
        remark: '',
        params: {},
        listItem: [
          {
            comboCode: "",
            foodDish: {
              foodName: "",
              foodId: "",
              type: ""
            }
          }
        ],
        description: ''
      }
      this.fileList = [] // 清空文件列表
      this.$nextTick(() => {
        this.$refs.foodForm && this.$refs.foodForm.clearValidate()
      })
    },
  
    // 提交表单
    async handleSubmit(val) {
      try {
        await this.$refs.foodForm.validate()
        
        // 检查是否至少上传了一张图片
        // if (!this.form.coverImage || JSON.parse(this.form.coverImage || '[]').length === 0) {
        //   this.$message.warning('请上传至少一张图片')
        //   return
        // }
        
        this.submitting = true
        
        // 设置创建人
        this.form.createBy = this.$store.state.user.name

        // 处理菜品信息
        this.form.listItem.forEach(els => {
          els.foodDish.foodName = this.ingredientList.filter(el => el.foodId == els.foodDish.foodId)[0]?.foodName || ''
          const T = this.ingredientList.filter(el => el.foodId == els.foodDish.foodId)[0]?.foodCode
          const Ts = this.ingredientList.filter(el => el.foodId == els.foodDish.foodId)[0]?.foodId
          els.foodDish.foodCode = T
          els.foodCode = T
          els.foodId = Ts
        })

        // 处理开放时间
        for (let index = 0; index < 8; index++) {
          this.form['day' + (index + 1)] = 0
        }
        this.form.openingHours.forEach(el => {
          this.form['day' + el] = 1
        })

        delete this.form.openingHours

        // 如果没有审核权限，设置为审核中状态
        if (this.$store.state.user.permissions.filter(el => el == "food:combo:approval").length < 1) {
          this.form.status = 2
        }

            if (this.form.type == "早餐") {
              this.form.type = 1
            }

            if (this.form.type == "午餐") {
              this.form.type = 2
            }

            if (this.form.type == "晚餐") {
              this.form.type = 3
            }

        if (this.form.comboId) {
          // 更新套餐
          await ComboUpdate(this.form)
          this.$message.success('套餐更新成功')
        } else {
          // 新增套餐
          await ComboAdd(this.form)
          this.$message.success('套餐新增成功')
        }
        if (val == 1) {
           setTimeout(() => {
          this.$router.push("/cookbook")
        },200)
        }
       
        
        this.dialogVisible = false
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error(error)
          this.$message.warning('请完善表单信息')
        }
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style scoped>
::v-deep .pervoewClass .el-dialog{
    background: none;
    box-shadow: none;
}
.my-recipe-btn {
  /* 正常态 */
  color: #F68812;                 /* 文字色 */
  background-color: rgb(255, 250, 241);      /* 背景色 */
  border: 1px solid #F68812;

  /* hover 态 */
  &:hover {
    color: #fff;
    background-color: #F68812;
    border-color: #F68812;
  }

  /* 按下的 active 态 */
  &:active {
    color: #fff;
    background-color: #F68812;
    border-color: #F68812;
  }

  /* 禁用态（可选） */
  &.is-disabled {
    color: #c0c4cc;
    background-color: #fdf6ec;
    border-color: #fbeccd;
  }
}
::v-deep .el-dialog__headerbtn .el-dialog__close{
  font-size: 25px;
}
::v-deep .el-dialog{
  border-radius: 15px;
}
::v-deep .el-form--label-top .el-form-item__label{
  padding: 0;
}
.approval-container {
  padding: 20px;
  background: #fff;
}

.search-wrapper {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-direction: column;
}

.search-row {
  display: flex;
  margin-bottom: 15px;
}

.search-row .el-form-item {
  margin-right: 20px;
  margin-bottom: 0;
}

.search-actions {
  margin-left: auto;
}

.status-filter {
  margin-bottom: 15px;
}

.table-wrapper {
  margin-top: 20px;
}

.content-cell {
  padding: 5px 0;
}

.content-cell p {
  margin: 5px 0;
  line-height: 1.5;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.el-table::before {
  display: none;
}
::v-deep .el-dialog__body{
  padding-top: 8px;
}

.el-table {
  border: none;
}

.el-table /deep/ th {
  border-bottom: 1px solid #ebeef5;
}

.el-table /deep/ td {
  border-bottom: 1px solid #ebeef5;
}

.el-input-number {
  width: 100%;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
  background-color: #4C6EE2;
  border: 1px solid #4C6EE2;
  color: black;
}

::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: black;
}

::v-deep .el-form-item {
  margin-bottom: 8px;
  margin-right: 0;
}

::v-deep .el-input--medium .el-input__inner {
  height: 32px;
  line-height: 32px;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0);
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.2);
}

::v-deep .dialogN .el-input--medium .el-input__inner {
  height: 42px;
  line-height: 42px;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0);
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.2);
}

/* 上传组件样式调整 */
/* ::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
}
::v-deep .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
} */
</style>